Navigation

  • index
  • next |
  • previous |
  • PyHowTo documentation »
  • Basic »
  • Math »

Table of Contents

Python v3.7 HowTos:

  • ----------------
  • Recursion
  • Backtracking
  • Dynamic Programming
  • Greedy
  • Sort
  • Binary Search
  • Depth First Search [DFS]
  • Breadth First Search [BFS]
  • Binary Search Tree [BST]
  • ----------------
  • Array
  • String
  • Heap
  • Stack
  • Queue
  • Tree
  • Linked List
  • Hash Table
  • Bit Manipulation
  • Two Pointers
  • Math
  • Decorator
  • ----------------
  • Basic
  • Intermediate
  • Advanced
  • Interview
  • ----------------
  • Spark
  • Tkinter
  • Turtle
  • Games
  • Web
  • ----------------
  • About
  • History

Previous topic

Returns sum of all divisors of a number

Next topic

Print the first N lucky numbers

Quick search

Print all permutations of a given string (incl. duplicates)ΒΆ

Print all permutations of a given string (including duplicates).
def permute_string(S):

    if len(S) == 0:
        return ['']

    prev_list = permute_string(S[1:len(S)])
    next_list = []

    for i in range(0, len(prev_list)):
        for j in range(0, len(S)):
            new_str = prev_list[i][0:j] + S[0] + prev_list[i][j:len(S)-1]
            if new_str not in next_list:
                next_list.append(new_str)

    return next_list

# test
print(permute_string('ABCD'))

Output:

['ABCD', 'BACD', 'BCAD', 'BCDA', 'ACBD', 'CABD', 'CBAD', 'CBDA',\
 'ACDB', 'CADB', 'CDAB', 'CDBA', 'ABDC', 'BADC', 'BDAC', 'BDCA', \
 'ADBC', 'DABC', 'DBAC', 'DBCA', 'ADCB', 'DACB', 'DCAB', 'DCBA']

See also

https://www.w3resource.com/python-exercises/math/python-math-exercise-16.php

Navigation

  • index
  • next |
  • previous |
  • PyHowTo documentation »
  • Basic »
  • Math »
© Copyright 2020, Sergiy Zaytsev, szaytsev@hotmail.com. Created using Sphinx 2.3.0.